from tkinter import Toplevel

from tkinter.scrolledtext import ScrolledText
from tkinter import Text
from tkinter import Button
from tkinter import END, UNITS
from time import localtime, strftime, time

class WindowChat(Toplevel):


    def __init__(self):
        super(WindowChat, self).__init__()
        self.geometry("900x600")
        self.resizable(False, False)

        self.addWidget()

        self.on_send_click(lambda :self.append_message('1', '1'))

    def addWidget(self):

        #聊天区
        chat_text_area = ScrolledText(self, name='chat_text_area')
        chat_text_area['width'] = 110
        chat_text_area['height'] = 30
        chat_text_area.grid(row=0, column=0, columnspan=2)
        chat_text_area.tag_config('green', foreground='#008800')
        self.children['chat_text_area'] = chat_text_area


        #输入框
        chat_input_area = Text(self, name='chat_input_area')
        chat_input_area['width'] = 100
        chat_input_area['height'] = 7
        chat_input_area.grid(row=1, column=0,pady=10)

        #发送按钮
        send_buttton = Button(self, name='send_buttton')
        send_buttton['width'] = 5
        send_buttton['height'] = 2
        send_buttton['text'] = '发送'
        send_buttton.grid(row=1, column=1)

    def set_title(self, title):
        self.title('欢迎'+title+'加入聊天室')

    def on_send_click(self, command):
        self.children['send_buttton']['command'] = command

    def get_input(self):
        return self.children['chat_input_area'].get(0.0,END)

    def clear_input(self):
        self.children['chat_input_area'].delete(0.0, END)


    def append_message(self, sender, message):

        send_time = strftime('%Y-%m-%d %H:%M:%S', localtime(time()))
        send_info = '%s:%s \n'%(sender, send_time)

        self.children['chat_text_area'].insert(END, send_info, 'green')
        self.children['chat_text_area'].insert(END, message + '\n')

        self.children['chat_text_area'].yview_scroll(3, UNITS)

    def on_window_close(self, command):
        self.protocol('WM_DELETE_WINDOW', command)


if __name__ == '__main__':
    window = WindowChat()
    window.mainloop()